using System.Collections;
using System.Collections.Generic;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.Profiling;

public class TestJobSystem : MonoBehaviour
{
    struct Job1 : IJob
    {
        public NativeArray<float> Values;
        public float Offset;

        public void Execute()
        {
            for (int i = 0; i < Values.Length; i++)
            {
                Values[i] += Offset;
            }
        }
    }

    struct Job2 : IJobParallelFor
    {
        [ReadOnly] public NativeArray<float> Copy;
        public NativeArray<float> Values;

        public void Execute(int index)
        {
            Values[index] = Copy[index];
        }
    }

    void Update()
    {
        // TestJob1();
        TestJob2();
        // TestNativeArray();
    }

    private void TestJob1()
    {
        Profiler.BeginSample("TestJob1");
        var values = new NativeArray<float>(500, Allocator.Persistent);
        var job = new Job1()
        {
            Values = values,
            Offset = 5f,
        };

        for (int i = 0; i < 1000; i++)
        {
            JobHandle jobHandle = job.Schedule();
            jobHandle.Complete();
        }

        values.Dispose();
        Profiler.EndSample();
    }

    private void TestJob2()
    {
        Profiler.BeginSample("TestJob2");
        var values = new NativeArray<float>(500, Allocator.Persistent);
        var copy = new NativeArray<float>(500, Allocator.Persistent);
        for (int i = 0; i < copy.Length; i++)
        {
            copy[i] = Random.Range(0, int.MaxValue);
        }
        
        var job = new Job2()
        {
            Values = values,
            Copy = copy,
        };

        for (int i = 0; i < 1000; i++)
        {
            JobHandle jobHandle = job.Schedule(values.Length, 32);
            jobHandle.Complete();
        }

        values.Dispose();
        copy.Dispose();
        Profiler.EndSample();
    }

    void TestNativeArray()
    {
        Profiler.BeginSample("NativeArray");
        NativeArray<Vector3> velocityN = new NativeArray<Vector3>(1000, Allocator.Persistent);
        for (int i = 0; i < velocityN.Length; i++)
        {
            velocityN[i] = Vector3.zero;
        }

        Profiler.EndSample();
        velocityN.Dispose();


        Profiler.BeginSample("Vector3[]");
        Vector3[] velocityA = new Vector3[1000];
        for (int i = 0; i < velocityA.Length; i++)
        {
            velocityA[i] = Vector3.zero;
        }

        Profiler.EndSample();
    }
}